/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-06-04 16:04:54
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-06-06 16:31:50
 * @FilePath: \vue3_upload_file\service\router\cut.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-06-04 16:04:54
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-06-06 15:16:06
 * @FilePath: \vue3_upload_file\service\router\cut.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const path = require('path');
const fse = require('fs-extra');
const Router = require('koa-router');
const { koaBody } = require('koa-body');

const {
  UPLOAD_DIR,
  extractExt,
  createUploadedList,
  mergeFileChunk,
  pipeStream
} = require('../utils/upload');
const { getDB } = require('../modules/db');

const router = new Router();

// 上传chunk
router.post('/cut', koaBody({ multipart: true }), async (ctx, next) => {
  // 参数请求体
  const { chunkHash, fileHash } = ctx.request.body;
  const { chunk } = ctx.request.files;
  // 切片输出目录
  const chunkDir = path.resolve(UPLOAD_DIR, `${fileHash}-chunks`);

  // 切片目录不存在，创建切片目录
  if (!fse.existsSync(chunkDir)) {
    // 创建切片目录
    await fse.mkdirs(chunkDir);
  }

  // 移动切片到切片目录
  await fse.move(chunk.filepath, `${chunkDir}/${chunkHash}`);

  ctx.body = {
    success: true,
    code: 200,
    msg: '上传成功'
  };
});

// chunk合并
router.post('/merge', async (ctx, next) => {
  // 参数请求体
  const { fileName, fileSize, size, hash } = ctx.request.body;
  // 文件名后缀
  const ext = extractExt(fileName);
  // 文件路径
  const filePath = path.resolve(UPLOAD_DIR, `${hash}${ext}`);
  // 切片目录
  const chunkDir = path.resolve(UPLOAD_DIR, `${hash}-chunks`);
  // 合并切片
  await mergeFileChunk(filePath, chunkDir, size);
  
  ctx.body = {
    success: true,
    code: 200,
    msg: '合并成功'
  };
});

// 验证文件是否存在
router.post('/verify', koaBody({ multipart: true }), async (ctx, next) => {
  // 参数请求体
  const { fileName, fileHash } = ctx.request.body;
  // 是否需要上传
  let isUpload = true;
  let msg = '文件不存在，需要上传';
  // 文件名后缀
  const ext = extractExt(fileName);
  // 文件路径
  const filePath = path.resolve(UPLOAD_DIR, `${fileHash}${ext}`);
  // 文件存在
  if (fse.existsSync(filePath)) {
    isUpload = false;
    msg = '文件已存在，不需要上传';
  }

  ctx.body = {
    success: true,
    code: 200,
    data: {
      isUpload,
      uploadList: await createUploadedList(fileHash),
      msg
    }
  };
});


module.exports = router;
